package Algorithm;

import java.util.*;

public class SortMap
{
    public static Map<String, String> sortMapByValueDesc(Map<String, String> oriMap) {
        Map<String, String> sortedMap = new LinkedHashMap<String, String>();
        try {
            if (oriMap != null && !oriMap.isEmpty()) {
                List<Map.Entry<String, String>> entryList = new ArrayList<Map.Entry<String, String>>(oriMap.entrySet());
                Collections.sort(entryList,
                        new Comparator<Map.Entry<String, String>>() {
                            public int compare(Map.Entry<String, String> entry1,
                                               Map.Entry<String, String> entry2) {
                                int value1 = 0, value2 = 0;
                                try {
                                    value1 = Integer.parseInt(entry1.getValue());
                                    value2 = Integer.parseInt(entry2.getValue());
                                } catch (NumberFormatException e) {
                                    value1 = 0;
                                    value2 = 0;
                                }
                                return value2 - value1;
                            }
                        });
                Iterator<Map.Entry<String, String>> iter = entryList.iterator();
                Map.Entry<String, String> tmpEntry = null;
                while (iter.hasNext()) {
                    tmpEntry = iter.next();
                    sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
                }
            }
        } catch (Exception e) {
        }
        return sortedMap;
    }
}
